/**
  计算机等级考试-创建考试
*/
<template>
  <div class="exam-create-container">
    <div v-if="indexKey === 1">
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{$t('mandarin.examList')}}</h1>
        <div class="edu-opertion-bar sub-title">
          <div class="float-right" style="display: flex;">
            <el-button v-if="permitToAdd" type="primary" @click="addExam()">{{$t('common.btn.add')}}</el-button>
          </div>
        </div>
        <edu-table :pagination="false" :order='true' :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini" @selection-change="handleSelectionChange">
          <edu-table-column :label="$t('subjectCompetitionBase.semester')" prop="calendarYearTerm"></edu-table-column>
          <edu-table-column :label="$t('mandarin.contestTitle')" prop="title"></edu-table-column>
          <edu-table-column :label="$t('computerGrade.examType')" prop="competitionType"></edu-table-column>
          <edu-table-column :label="$t('mandarin.registrationTime')" prop="signUpTime"></edu-table-column>
          <edu-table-column :label="$t('subjectCompetitionBase.status')" prop="status">
            <template slot-scope="scope">
              <div class="status-container">
                <el-button v-if="scope.row.status === '报名结束'" type="info" plain>{{ scope.row.status }}</el-button>
                <el-button v-else-if="scope.row.status === '未开始'" type="primary" plain>{{ scope.row.status }}</el-button>
                <el-button v-else type="success" plain>{{ scope.row.status }}</el-button>
              </div>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('common.text.operation')" fit width="300">
            <template slot-scope="scope">
              <el-button type="text" @click="changeExamEnable(scope.row)">
                <span v-if="scope.row.isEnabled === 1 && permitToClose">{{ $t('subjectCompetitionBase.close') }}</span>
                <span v-if="!scope.row.isEnabled && permitToOpen">{{ $t('subjectCompetitionBase.open') }}</span>
              </el-button>
              <el-button v-if="permitToEdit" type="text" @click="editExam(scope.row)">{{$t('common.btn.edit')}}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryForm.pageNum_"
              :page-sizes="[20, 40, 80, 100]"
              :page-size="queryForm.pageSize_"
              layout="total, sizes, prev, pager, next, jumper"
              :total="queryForm.total_"
              style="float:right;margin-top:10px"
            ></el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <!-- 新增/编辑考试开始 -->
    <div v-if="indexKey === 2">
      <operate-exam-create
        :operateMode="operateMode"
        :operateData="operateData"
        :rows="rows"
        @change-exam-create-index="changeExamCreateIndex">
      </operate-exam-create>
    </div>
    <!-- 新增/编辑考试结束 -->
  </div>
</template>
<script>
import operateExamCreate from './operateExamCreate';
import graduateStudentApi from 'common/src/api/graduateStudent/graduateStudent';
import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
export default {
  components: {
    'operate-exam-create': operateExamCreate
  },
  data () {
    return {
      rows:{},
      auths: [],
      indexKey: 1,
      permitToAdd: false,
      permitToOpen: false,
      permitToClose: false,
      permitToEdit: false,
      innerVisible: false,
      multipleSelection: [],
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        total_: 0,
        condition: {
          "educationTag": 1,
          "examCategory": 3
        }
      },
      operateMode: 'add',
      operateData: {
        contestTitle: '',
        semester: '',
        registrationStartTime: '',
        registrationEndTime: '',
        listSet: '',
        examExplanation: ''
      },
      dataList: [],
      examId: ''
    }
  },
  filters: {
    status(val) {
      switch (val) {
        case 0:
          return '报名结束'
        case 1:
          return '正在报名'
        default:
          return val
      }
    }
  },
  created() {
    // 获取当前用户auths权限
    if (localStorage.getItem("sessiondata")) {
      if (JSON.parse(localStorage.getItem("sessiondata")).auths) {
        this.auths = JSON.parse(localStorage.getItem("sessiondata")).auths
      }
    }
    this.onSubmit()
  },
  methods: {
    getListData() {
      subjectCompetitionApi.getPutonghuaExamsList(this.queryForm).then((res) => {
        this.dataList = res.data.list;
        this.queryForm.total_ = res.data.total_;
      })
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getListData()
    },
    // 新增考试
    addExam() {
      this.operateMode = 'add'
      for (let key in this.operateData) {
        this.operateData[key] = ''
      }
      this.indexKey = 2
    },
    // 返回列表页
    changeExamCreateIndex() {
      this.indexKey = 1
      this.onSubmit()
    },
    // 编辑考试
    async editExam(row) {
      this.rows=row;
      // let endTime = new Date(row.signUpEnd.replace('-', '/')).getTime()
      // let nowTimeResponse = await graduateStudentApi.getCurrentSystemTime()
      // if (nowTimeResponse.data) {
      //   nowTimeResponse.data = new Date(nowTimeResponse.data).getTime()
      // }
      // if (!(nowTimeResponse.data <= endTime)) {
      //   this.$eduConfirm(this.$t('mandarin.registEndTime') + '（' + row.signUpEnd + '）已过').then(_ => {})
      //   return
      // }
      this.operateMode = 'edit'
      const detailInfo = await subjectCompetitionApi.selectPutonghuaExamDetail({
        id: row.id
      })
      const listInfo = await subjectCompetitionApi.selectRegistRosterNew({
        "pageNum_": 1,
        "pageSize_": 99999,
        "condition": {
          "competitionId": row.id,
          "leaveSchool": null,
          "registrationStatus": null,
          "enrolMethods": null,
          "name": null
        }
      })
      let operateData = {}
      if (detailInfo.code === 200) {
        operateData = detailInfo.data
        operateData['listSet'] = ''
        operateData.conflictType = operateData.conflictType ? operateData.conflictType : []
        operateData.lockLimit = operateData.lockLimit.toString()
      }
      if (listInfo.code === 200 && listInfo.data.list.length > 0) {
        let listArray = JSON.parse(JSON.stringify(listInfo.data.list))
        listArray.forEach(item => {
          item["id"] = item.id
          item['name'] = item.studentName
          item['faculty'] = item.college
          item['facultyI18n'] = item.collegeI18n
          item['leaveSchool'] = item.atSchoolStatus
          item['leaveSchoolI18n'] = item.atSchoolStatusI18n
          item['registrationStatus'] = item.studentStatus
          item['registrationStatusI18n'] = item.studentStatusI18n
        })
        operateData['listSet'] = listArray
      }
      this.operateData = operateData
      this.indexKey = 2
    },
    // 开启/关闭考试
    changeExamEnable(row) {
      subjectCompetitionApi.openOrOffPutonghuaExam({
        "id": row.id,
        "isEnabled": row.isEnabled === 0 ? 1 : 0  // 启停状态 0停用 1启用
      }).then(_ => {
        this.onSubmit()
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val
      this.getListData()
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val
      this.getListData()
    }
  },
  watch: {
    auths: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal) && newVal.length > 0) {
          newVal.some(item => {
            if (item.authCode === 'subjectCompetition-examCreate-add') {
              this.permitToAdd = true
            }
            if (item.authCode === 'subjectCompetition-examCreate-open') {
              this.permitToOpen = true
            }
            if (item.authCode === 'subjectCompetition-examCreate-close') {
              this.permitToClose = true
            }
            if (item.authCode === 'subjectCompetition-examCreate-edit') {
              this.permitToEdit = true
            }
          });
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
  .status-container ::v-deep {
    .el-button {
      cursor: auto;
    }
    // .el-button--info {
    //   padding: 9px 21px;
    //   min-width: 0;
    // }
  }
</style>
